// request


const hdUrl = 'http://localhost:3000/api'
const timeout = 5000;

export default async function request(params) {
  const baseUrl = params.baseUrl || hdUrl;
  let url = baseUrl + params.url;
  let method = params.method || 'GET';
  let data = params.data || {};
  let header = {
    'content-type': 'application/json', // 默认值
    ...params.header, // 合并自定义 header
  };

  // 获取token
  const token = uni.getStorageSync('token');

  // 如果有token,添加到请求头
  if (token) {
    header['Authorization'] = `Bearer ${token}`;
  }

  // 如果是 GET 请求，将 data 转换为查询字符串
  if (method === 'GET' && Object.keys(data).length > 0) {
    const queryString = Object.keys(data)
      .map(key => `${key}=${encodeURIComponent(data[key])}`)
      .join('&');
    url += `?${queryString}`;
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: method,
      header: header,
      data: method === 'GET' ? undefined : data, // GET 请求无需传 data
      timeout: timeout,

      success(res) {
        if (res.statusCode === 200) {
          resolve(res.data); // 返回成功数据
        } else if (res.statusCode === 401) {
          // 清除token
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');

          // 跳转到登录页
          uni.navigateTo({
            url: '/pages/login/login'
          });

          reject(new Error('登录已过期,请重新登录'));
        } else {
          reject(new Error(`请求失败：${res.statusCode} - ${res.data.message}`));
        }
      },

      fail(err) {
        reject(new Error(`请求失败：${err.errMsg}`));
      },
    });
  });
}